﻿using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace ProjectN.Core.Fore
{
    public partial class ImageDisplay : UserControl
    {
        private static readonly Size EXTSIZE = new Size(17, 17);
        private static readonly Bitmap EMPTY_IMAGE = new Bitmap(1, 1);
        protected float scaling;
        protected Size displaySize;
        protected Size currentImageSize;
        protected Image image;
        protected FrameInfo frameInfo;
        public ImageDisplay()
        {
            InitializeComponent();
            this.image = EMPTY_IMAGE;
            this.frameInfo = default(FrameInfo);
        }

        [Category("Image Display"), Description("缩放倍率"), DefaultValue(1.00)]
        public float Scaling
        {
            get { return this.scaling; }
            set
            {
                this.scaling = value;
                this.UpdateImageInfo();
            }
        }

        [Category("Image Display"), Description("图片"), DefaultValue(null)]
        public Image Image
        {
            get { return this.image; }
            set
            {
                this.image = value;
                this.UpdateImageInfo();
            }
        }

        [Category("Image Display"), Description("图片显示区大小"), DefaultValue(typeof(Size), "100, 100")]
        public Size DisplaySize
        {
            get { return this.displaySize; }
            set
            {
                this.displaySize = value;
                base.Size = Size.Add(this.displaySize, EXTSIZE);
                this.UpdateImageInfo();
            }
        }

        [Category("Image Display"), Description("框架信息"), DefaultValue(typeof(FrameInfo), "0, 0, 0, 0")]
        public FrameInfo FrameInfo
        {
            get { return this.frameInfo; }
            set
            {
                this.frameInfo = value;
                this.Update();
            }
        }

        public Point CursorPositionOnImage
        {
            get
            {
                Point newPos = Point.Subtract(Point.Subtract(this.PointToClient(Cursor.Position), (Size)this.AutoScrollPosition), (Size)this.FrameInfo.TopP);
                return Point.Round(new PointF(newPos.X / this.Scaling, newPos.Y / this.Scaling));
            }
        }

        private void UpdateImageInfo()
        {
            this.currentImageSize = new Size(
                (int)(this.DisplaySize.Width * this.Scaling),
                (int)(this.DisplaySize.Height * this.Scaling)
            );

            this.AutoScrollMinSize = Size.Add(this.currentImageSize, new Size(0, this.FrameInfo.FinY));
        }

        private void ImageDisplay_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
            e.Graphics.DrawImage(this.Image, new RectangleF(Point.Add(this.AutoScrollPosition, (Size)this.frameInfo.TopP), this.currentImageSize));
        }
    }
}
